package cn.tedu.javacv.util;

import org.bytedeco.javacpp.opencv_core.Mat;
import org.bytedeco.javacpp.opencv_imgcodecs;
import org.bytedeco.javacpp.opencv_videoio;
import org.bytedeco.javacpp.opencv_videoio.VideoCapture;


public class VideoToImages {

    public static void main(String[] args) {
        String videoFilePath = "C:\\Users\\white\\Desktop\\bird.mp4";
        String outputFolderPath = "C:\\Users\\white\\Desktop\\img";

        try {
            captureFrames(videoFilePath, outputFolderPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void captureFrames(String videoFilePath, String outputFolderPath) throws Exception {
        VideoCapture capture = new VideoCapture(videoFilePath);
        if (!capture.isOpened()) {
            throw new Exception("Error opening video file.");
        }

        double frameRate = capture.get(opencv_videoio.CAP_PROP_FPS); // 获取视频帧率
        double targetIntervalInSeconds = 0.5; // 目标间隔时间（0.5秒）
        int framesToSkip = (int) Math.round(frameRate * targetIntervalInSeconds); // 计算要跳过的帧数

        Mat frame = new Mat();
        int frameNumber = 0;

        while (capture.read(frame)) {
            if (frame.empty()) {
                break; // No more frames
            }

            if ((frameNumber % framesToSkip) == 0) { // 每隔特定帧数截取
                // Save the frame as an image file
                String outputFilePath = outputFolderPath + "/frame_" + frameNumber + ".jpg";
                opencv_imgcodecs.imwrite(outputFilePath, frame);

                // Display the frame (optional)
                // opencv_highgui.imshow("Video Frame", frame);
                // opencv_highgui.waitKey(10);
            }

            frameNumber++;
        }

        // Release resources
        capture.release();
        // opencv_highgui.destroyAllWindows(); // 如果不在GUI环境下运行，这行可以移除
    }
}




